package com.server.scanner;

import com.annnotion.Controller;
import com.annnotion.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * Created by Greg.chen on 2016-03-22.
 */
@Component
public class Scanner implements BeanPostProcessor {

    private final Logger logger = LoggerFactory.getLogger(Scanner.class);



    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<? extends Object> clazz = bean.getClass();

        if(!clazz.isAnnotationPresent(Controller.class))
            return bean;

        Method[] methods = clazz.getMethods();
        if(methods == null || methods.length == 0)
            return bean;

        for(Method method : methods) {
            RequestMapping requestMapping =  method.getAnnotation(RequestMapping.class);

            if(requestMapping == null)
                continue;

            String uri = requestMapping.uri();
            logger.debug("request mapping uri is "+ uri);

            InvokeHolder.addInvoker(uri, Invoker.valueOf(method, bean));
        }

        return bean;
    }
}
